#include "dialog.h"
#include <QDebug>


Dialog::Dialog(QString port, QWidget *parent) :
        QDialog(parent)
{
    socket = new QUdpSocket(this);
    int port_counter = port.toInt();

    qDebug()<< port_counter;
    if (!socket->bind(QHostAddress::LocalHost, port_counter))
    {
        QMessageBox::information(this, "Error", "Port " + port + " already used!");
        //++port_counter;
    }

    lwid = new QListWidget(this);

    QVBoxLayout *vlay = new QVBoxLayout(this);

    QHBoxLayout *hlay = new QHBoxLayout();
    QHBoxLayout *hlay2 = new QHBoxLayout();

    vlay ->addWidget(lwid, 50);
    vlay ->addLayout(hlay, 10);
    vlay ->addLayout(hlay2, 10);

    ipLine = new QLineEdit("192.168.56.1", this);
    hlay -> addWidget(ipLine);

    portLine = new QLineEdit("3305", this);
    hlay -> addWidget(portLine);

    greetingLine = new QLineEdit("Hello!", this);
    hlay2->addWidget(greetingLine);

    button = new QPushButton("send", this);
    hlay2->addWidget(button);

    setLayout(vlay);

    connect (button, SIGNAL(clicked()),this, SLOT(sendMessage()));
    connect (socket, SIGNAL(readyRead()), this, SLOT (readMessage()));
}

void Dialog::sendMessage(){
    QByteArray message;
    message.append(greetingLine->text());
    socket->writeDatagram(message, QHostAddress(ipLine->text()), portLine->text().toInt());
    QString text(message);
    lwid->addItem(text);

}

void Dialog::readMessage()
{
    while(socket->hasPendingDatagrams())
    {
        QByteArray message;
        quint16 maxlen = socket->pendingDatagramSize();
        message.resize(maxlen);

        socket->readDatagram(message.data(), maxlen, 0,0);
        QString text = message;
        lwid->addItem(text);
    }

}


